﻿using System;
using System.Collections.Generic;
using System.Drawing;

namespace HYRElectric.LightningCalculation
{
	internal class Triangle
	{
		public TriangleVertex Point1 { get; set; }

		public TriangleVertex Point2 { get; set; }

		public TriangleVertex Point3 { get; set; }

		public TriangleEdge Edge1 { get; set; }

		public TriangleEdge Edge2 { get; set; }

		public TriangleEdge Edge3 { get; set; }

		public TriangleVertex CircumCenter
		{
			get
			{
				return new TriangleVertex(this.CalCenter(this));
			}
		}

		public List<TriangleVertex> Points
		{
			get
			{
				return new List<TriangleVertex>
				{
					this.Point1,
					this.Point2,
					this.Point3
				};
			}
		}

		public Triangle(Triangle tri)
		{
			this.Point1 = tri.Point1;
			this.Point2 = tri.Point2;
			this.Point3 = tri.Point3;
		}

		public Triangle(TriangleVertex p1, TriangleVertex p2, TriangleVertex p3)
		{
			this.Point1 = p1;
			this.Point2 = p2;
			this.Point3 = p3;
		}

		public PointF CalCenter(Triangle triangle)
		{
			PointF result = default(Point);
			float x = triangle.Point1.Point.X;
			float y = triangle.Point1.Point.Y;
			float x2 = triangle.Point2.Point.X;
			float y2 = triangle.Point2.Point.Y;
			float x3 = triangle.Point3.Point.X;
			float y3 = triangle.Point3.Point.Y;
			result.X = ((y2 - y) * (y3 * y3 - y * y + x3 * x3 - x * x) - (y3 - y) * (y2 * y2 - y * y + x2 * x2 - x * x)) / (2f * (x3 - x) * (y2 - y) - 2f * ((x2 - x) * (y3 - y)));
			result.Y = ((x2 - x) * (x3 * x3 - x * x + y3 * y3 - y * y) - (x3 - x) * (x2 * x2 - x * x + y2 * y2 - y * y)) / (2f * (y3 - y) * (x2 - x) - 2f * ((y2 - y) * (x3 - x)));
			return result;
		}

		public bool ContainPoint(TriangleVertex p)
		{
			return this.Point1 == p || this.Point2 == p || this.Point3 == p;
		}

		public static TriangleEdge GetEdge(List<TriangleEdge> edges, Triangle angle)
		{
			foreach (TriangleEdge triangleEdge in edges)
			{
				if (angle.Edge1 == triangleEdge)
				{
					return angle.Edge1;
				}
				if (angle.Edge2 == triangleEdge)
				{
					return angle.Edge2;
				}
				if (angle.Edge3 == triangleEdge)
				{
					return angle.Edge3;
				}
			}
			return null;
		}

		public static List<TriangleEdge> GetEdges(List<Triangle> triangles)
		{
			List<TriangleEdge> list = new List<TriangleEdge>();
			foreach (Triangle triangle in triangles)
			{
				list.Add(triangle.Edge1);
				list.Add(triangle.Edge2);
				list.Add(triangle.Edge3);
			}
			if (list.Count == 0)
			{
				return null;
			}
			return list;
		}
	}
}
